﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.GridPerson;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.GridPerson
{
    /// <summary>
    /// 更新网格人员的处理类
    /// </summary>
    public class UpdateGridPersonHandler : IRequestHandler<UpdateGridPersonCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateGridPersonHandler> logger;

        //更新表:AccountModel  需要AutoMapper映射: IMapper  要记录日志:LogModel对应的仓储  Nlog日志组件
        
        /// <summary>
        /// 注入更新网格人员所需资源
        /// </summary>
        /// <param name="accountRepo">账号仓储</param>
        /// <param name="logRepo">日志仓储</param>
        /// <param name="mapper">映射组件</param>
        /// <param name="logger">Nlog日志组件</param>
        public UpdateGridPersonHandler(IBaseRepository<AccountModel> accountRepo, IBaseRepository<LogModel> logRepo,IMapper mapper,ILogger<UpdateGridPersonHandler> logger)
        {
            this.accountRepo = accountRepo;
            this.logRepo = logRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 更新网格人员的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateGridPersonCommand request, CancellationToken cancellationToken)
        {
            logger.LogInformation($"即将修改网格人员{request.RealName}的信息");
            //实例化响应包装类
            ApiResult<int> res = new ApiResult<int>();
            //根据id查找要修改的网格人员实体
            var account =await accountRepo.GetModel(request.Id);

            //判断实体是否为空,如果为空直接返回响应包装类对象
            if (account == null) {
                res.Msg = "要更新的账号数据不存在";
                res.Code = ApiEnum.Failed;
                return res;
                }
            //使用AutoMapper把修改网格人员请求命令里的参数映射到实体中
            account = mapper.Map(request, account);


            //使用仓储的更新方法持久化到数据库
            var r =await accountRepo.UpdateAsync(account);

            //判断是否更新成功,根据更新结果给响应包装类赋值
            if (r > 0)
            {
                res.Code = ApiEnum.Success;
                res.Data = r;
                res.Msg = "更新网格人员成功.";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Data = 0;
                res.Msg = "更新网格人员失败.";
            }

            logger.LogInformation($"修改网格人员{request.RealName}的信息完成");
            //返回响应包装类对象给前端
            return res;

        }
    }
}
